package com.bjpowernode.controller;

import com.bjpowernode.exception.ExceptionResult;
import com.bjpowernode.exception.GlobalException;
import com.bjpowernode.service.ProviderService;
import com.bjpowernode.util.Util;
import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "provide")
public class ProvideController {

    @Autowired
    private ProviderService providerService;

    @PostMapping("/provideFood.do")
    @ResponseBody
    public ExceptionResult addFood(@RequestParam("username")String username,
                                   @RequestParam("foodName")String foodName,
                                   @RequestParam("price")Float foodPrice,
                                   @RequestParam("count")Integer foodCount, HttpServletRequest request) throws Exception {
        FileItem file = Util.getFile(request, "file");
        if (file == null)
            throw new GlobalException("图片不能为空");
        providerService.addFood(username,file.getInputStream(),foodName, foodPrice, foodCount);
        return ExceptionResult.success();
    }

    @RequestMapping("/delFood.do")
    @ResponseBody
    public int delFood(@RequestParam("id")Integer id){
        return providerService.delFood(id);
    }

    @RequestMapping("/loadUserFood.do")
    public ModelAndView loadUserFood(@RequestParam("name")String username){
        ModelAndView mv = new ModelAndView();
        mv.addObject("food",providerService.selectUserFood(username));
        mv.setViewName("myProvide");
        return mv;
    }

    @RequestMapping(value = "/loadAllFood.do")
    public ModelAndView loadAllFood(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("food",providerService.loadAllFood());
        mv.setViewName("provide");
        return mv;
    }
}
